package org.cyrano.anim;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.view.View;

/**
 * @author Demián Gutierrez
 */
public class CustomDrawView extends View {

  private List<CircleSprite> circleSpriteList = new ArrayList<CircleSprite>();

  private long t1 = Long.MAX_VALUE;

  // --------------------------------------------------------------------------------

  public CustomDrawView(Context context) {
    super(context);

    CircleSprite circleSprite;

    circleSprite = new CircleSprite( //
        new PointF(100, 20), new PointF(60, 20), Color.GREEN, 40);
    circleSpriteList.add(circleSprite);

    circleSprite = new CircleSprite( //
        new PointF(100, 90), new PointF(10, 10), Color.WHITE, 20);
    circleSpriteList.add(circleSprite);

    circleSprite = new CircleSprite( //
        new PointF(250, 300), new PointF(20, -10), Color.RED, 20);
    circleSpriteList.add(circleSprite);

    circleSprite = new CircleSprite( //
        new PointF(10, 200), new PointF(-40, -10), Color.YELLOW, 20);
    circleSpriteList.add(circleSprite);
  }

  // --------------------------------------------------------------------------------

  protected void onDraw(Canvas canvas) {
    Paint paint = new Paint();

    paint.setColor(Color.DKGRAY);
    canvas.drawRect(0, 0, Hwh.getW(this), Hwh.getH(this), paint);

    for (CircleSprite circleSprite : circleSpriteList) {
      paint.setColor(circleSprite.getColor());

      canvas.drawCircle( //
          circleSprite.getCoord().x, //
          circleSprite.getCoord().y, //
          (float) circleSprite.getRad(), paint);
    }

    if (t1 != Long.MAX_VALUE) {
      float dt = (System.currentTimeMillis() - t1) / 1000.0f;

      for (CircleSprite circleSprite : circleSpriteList) {
        // Calculate X & Y
        circleSprite.getCoord().x = //
        circleSprite.getCoord().x + circleSprite.getSpeed().x * dt;

        circleSprite.getCoord().y = //
        circleSprite.getCoord().y + circleSprite.getSpeed().y * dt;

        // Normalize X & Y
        while (circleSprite.getCoord().x < 0) {
          circleSprite.getCoord().x = Hwh.getW(this) + circleSprite.getCoord().x;
        }

        circleSprite.getCoord().x %= Hwh.getW(this);

        while (circleSprite.getCoord().y < 0) {
          circleSprite.getCoord().y = Hwh.getH(this) + circleSprite.getCoord().y;
        }

        circleSprite.getCoord().y %= Hwh.getH(this);
      }
    }

    invalidate();

    t1 = System.currentTimeMillis();
  }
}
